package com.example.memoapp.fragments;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.memoapp.R;
import com.example.memoapp.activities.MemoDetailActivity;
import com.example.memoapp.adapters.MemoAdapter;
import com.example.memoapp.database.MemoDatabaseHelper;
import com.example.memoapp.models.Post;

import java.util.ArrayList;
import java.util.List;

public class MemoListFragment extends Fragment implements MemoAdapter.OnPostClickListener {

    private RecyclerView recyclerView;
    private MemoAdapter adapter;
    private MemoDatabaseHelper dbHelper;
    private List<Post> postList = new ArrayList<>();

    public static MemoListFragment newInstance() {
        return new MemoListFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_memo_list, container, false);

        recyclerView = view.findViewById(R.id.recycler_view_memos); // 确保布局文件中有RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        dbHelper = new MemoDatabaseHelper(getActivity());

        loadMemos();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadMemos();
    }

    private void loadMemos() {
        // 将Cursor数据转换为Post列表
        postList = cursorToList(dbHelper.getAllMemos());

        if (adapter == null) {
            adapter = new MemoAdapter(postList, this);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    private List<Post> cursorToList(Cursor cursor) {
        List<Post> posts = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                Post post = new Post();
                post.setId(cursor.getInt(cursor.getColumnIndex(MemoDatabaseHelper.COLUMN_ID)));
                post.setTitle(cursor.getString(cursor.getColumnIndex(MemoDatabaseHelper.COLUMN_TITLE)));
                post.setContent(cursor.getString(cursor.getColumnIndex(MemoDatabaseHelper.COLUMN_CONTENT)));
                // 设置其他字段...
                posts.add(post);
            } while (cursor.moveToNext());
            cursor.close();
        }
        return posts;
    }

    @Override
    public void onPostClick(Post post) {//通过主Activity跳转
        Intent intent = new Intent(getActivity(), MemoDetailActivity.class);
        intent.putExtra("memoId", post.getId());
        startActivity(intent);
    }
}